/**
 * 输入: nums=[-1, 2, 1, -4], target=1
 * 输出: 2
 * 解释: 与target最接近的数是2 (-1 + 2 + 1 = 2)
 * */
function threeSumClosest (nums, target) {
    let result;
    // 先排序
    nums.sort((a, b) => a - b);
    for (let i = 1; i < nums.length; i++) {
         // 定义左右指针
        let left = i + 1;
        let right = nums.length - 1;
        // 左右指针向中间靠拢
        while (left < right) {
            result = nums[i] + nums[left] + nums[right];
            // 与目标值对比，小了左指针加，大了右指针减
            if (result < target) {
                left++;
            } else if (result > target) {
                right--;
            } else {
                break;
            }
        }
    }
    return result;
}
console.log(threeSumClosest([-1, 2, 1, -4], 1));